package com.woniuxy.controller;

import com.woniuxy.entity.WebSocketMessage;
import com.woniuxy.mapper.WebSocketMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Component
// 配置WebSocket端点，{userId}表示连接时需要传入用户ID
@ServerEndpoint("/ws/chat/{phoneNumber}")
public class WebSocketService {
    private static WebSocketMessageMapper webSocketMessageMapper;
    @Autowired
    public void setWebSocketMessageMapper(WebSocketMessageMapper webSocketMessageMapper) {
        WebSocketService.webSocketMessageMapper = webSocketMessageMapper;
    }
    // 存储用户ID与WebSocket会话的映射
    private static ConcurrentHashMap<String, Session> userSessionMap = new ConcurrentHashMap<>();
    // 当前连接的用户手机号
    private String phoneNumber;
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("phoneNumber") String phoneNumber) {
        this.phoneNumber = phoneNumber;
        userSessionMap.put(phoneNumber, session);
        System.out.println("用户：" + phoneNumber + "已连接");
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        userSessionMap.remove(phoneNumber);
        System.out.println("用户：" + phoneNumber + "已断开");
    }

    @OnMessage
    public void onMessage(String message,Session session){
        try {
            String[] parts = message.split(":",2);
            if (parts.length != 2){
                sendMessageToUser(phoneNumber,"无效的消息格式");
                return;
            }
            String receiverPhone = parts[0];
            String content = parts[1];
            WebSocketMessage webSocketMessage = new WebSocketMessage();
            webSocketMessage.setSenderPhone(phoneNumber);
            webSocketMessage.setReceiverPhone(receiverPhone);
            webSocketMessage.setMessageContent(content);
            webSocketMessage.setSendTime(LocalDateTime.now());
            webSocketMessage.setIsRead(0);
            webSocketMessageMapper.add(webSocketMessage);
            Session receiverSession = userSessionMap.get(receiverPhone);
            if (receiverSession != null && receiverSession.isOpen()) {
                receiverSession.getBasicRemote().sendText(phoneNumber + ":" + content);
            } else {
                sendMessageToUser(phoneNumber,"用户未在线");
            }
        }catch (Exception e){
            e.printStackTrace();
            try {
                sendMessageToUser(phoneNumber,"发送消息失败");
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }
    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("用户：" + phoneNumber + "发生错误");
        error.printStackTrace();
    }
    /**
     * 发送消息给指定用户
     */
    public static void sendMessageToUser(String phoneNumber, String message) throws IOException {
        Session session = userSessionMap.get(phoneNumber);
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }
}
